<style lang="stylus">
.history-list
  // min-height 100%
  overflow hidden
  padding-top 188px
  .title-bar
    width 100%
    max-width 750px;/*no*/
    position fixed
    top 0
    z-index 9
  .empty-data
    margin-top 70px
  .see-recommend
    background-color #5142be
    border-radius 6px
    line-height 80px
  .blue
    color 4f42c1
  .check-menu
    position fixed
    width 100%
    height 90px
    line-height 90px
    bottom 0
    left 0
    z-index 9
    > div
      height 100%
      flex-basis 0
  .right-arrow
    background url("../assets/detail/right_arrow_black.png") no-repeat right center
    background-size 13px 21px
</style>

<template lang="pug">
.history-list.relative
  title-bar(:title="isFavor ? '我的收藏': '历史记录'")
    .fz-28.pdr-22(v-if="items.length", @click="onEdit") {{!this.showCheck ? '编辑': '取消'}}
  template(v-if="loadDone && !items.length")
    .empty-data
    .fz-22.gray-99.center.mgt-20 {{isFavor ? '你没有收藏的影片哦': '你没有观看过影片哦'}}
    .see-recommend.mg-52.white.fz-36.center(@click="onGoHome") 查看精选影片
    .flex.pdh-20.mgt-50(v-if="recommends.length")
      .fz-28.bold 猜你喜欢
      .flex-1
      .fz-26.right-arrow.pdr-20(@click="onLinkPage('/home')") 全部
    search-item.pdh-20(v-for="(recommend, index) in recommends", :key="index", :item="recommend", :class="{'pdt-30': index === 0}")
  search-item(v-for="(item, index) in items", :key="index", :item="item.data || item", :showCheck="showCheck",
    @check="toggleCheck", :checked="checkedIndex(item.movieId || item.data.movieId) !== -1", :class="{'pdt-30': index === 0}")
  .loading-more.center.fz-30.pdv-20(v-show="showMoreLoading") 加载中...
  no-more(v-if="!hasMore && items.length")
  .check-menu.fz-32.bold.flex.bg-white.bdt(v-show="showCheck")
    .dark.flex-1.center(@click="onFullSelect") {{isFullSelect ? '取消全选': '全选'}}
    .blue.flex-1.center.bdl(@click="onDeleteSelect") 删除
</template>

<script>
import TitleBar from '../components/TitleBar.vue'
import SearchItem from '../components/SearchItem.vue'
import paging from '../mixin/paging'
import { CACHE_KEY } from '../const'

export default {
  name: 'history-list',
  mixins: [paging],
  components: { TitleBar, SearchItem },
  data() {
    return {
      recommends: [],
      isFavor: true,
      showCheck: false,
      checkedIds: []
    }
  },

  mounted() {
    this.isFavor = this.$route.query.type === 'favor'

    if (this.isFavor) {
      this.fetch().then(this.loadRecommendList)
    } else {
      const movieIds = this.getStore(CACHE_KEY.BROWSER_HISTORY) || []
      if (movieIds.length) {
        this.$get('movie/list/batch', {
          movieIds: movieIds.join(',')
        }).then(items => {
          this.items = items || []
          this.hasMore = false
          this.loadDone = true
          this.loadRecommendList()
        })
      } else {
        this.hasMore = false
        this.loadDone = true
        this.loadRecommendList()
      }
    }
  },

  computed: {
    paging() {
      if (!this.isFavor) {
        return
      }

      return {
        path: 'user/collect/list',
        params: {
          userId: this.user.userId
        }
      }
    },

    isFullSelect() {
      return this.checkedIds.length === this.items.length
    }
  },

  methods: {
    loadRecommendList() {
      if (this.items.length) { // 没有加载到数据才需加载猜你喜欢
        return
      }

      // 推荐列表
      this.$get('movie/recommend', { num: 20, userId: this.userId }).then(recommends => {
        this.recommends = recommends
      })
    },

    onEdit() {
      this.showCheck = !this.showCheck
    },

    checkedIndex(movieId) {
      return this.checkedIds.findIndex(id => movieId === id)
    },

    toggleCheck(movieId) {
      const idx = this.checkedIndex(movieId)
      if (idx !== -1) {
        this.checkedIds.splice(idx, 1)
      } else {
        this.checkedIds.push(movieId)
      }
    },

    onFullSelect() {
      if (!this.isFullSelect) {
        this.checkedIds = this.items.map(item => item.movieId || item.data.movieId)
      } else {
        this.checkedIds = []
      }
    },

    onDeleteSelect() {
      if (!this.checkedIds.length) {
        this.$toast('请先选择删除的目标')
        return
      }

      if (this.isFavor) {
        const deleteFavorIds = []
        this.checkedIds.forEach(id => {
          const targetItem = this.items.find(item => +item.data.movieId === +id)
          if (targetItem) {
            deleteFavorIds.push(targetItem.id)
          }
        })

        this.$get('user/collect/delete', { ids: deleteFavorIds.join(',') }).then(() => {
          this.$toast('删除成功')

          deleteFavorIds.forEach(id => {
            const targetItemIdx = this.items.findIndex(item => +item.id === +id)
            if (targetItemIdx !== -1) {
              this.items.splice(targetItemIdx, 1)
            }
          })

          if (!this.items.length) { // 删除完成，显示猜你喜欢
            this.loadRecommendList()
            this.showCheck = false
          }
        })
      } else {
        const movieIds = this.getStore(CACHE_KEY.BROWSER_HISTORY) || []
        this.checkedIds.forEach(id => {
          const targetItemIdx = this.items.findIndex(item => +item.movieId === +id)
          if (targetItemIdx !== -1) {
            this.items.splice(targetItemIdx, 1)
          }

          const targetStoreIdx = movieIds.findIndex(movieId => +movieId === +id)
          if (targetStoreIdx !== -1) {
            movieIds.splice(targetStoreIdx, 1)
          }
        })

        if (!this.items.length) { // 删除完成，显示猜你喜欢
          this.loadRecommendList()
          this.showCheck = false
        }
        this.saveStore(CACHE_KEY.BROWSER_HISTORY, movieIds)
        this.$toast('删除成功')
      }
    },
    onGoHome() {
      if (this.config.env.isBrowser) {
        this.onLinkPage('/home')
      } else {
        this.action('home')
      }
    },
  }
}
</script>
